import tushare as ts
from datetime import datetime, timedelta

class TradingStrategy:
    def __init__(self, stock):
        self.stock = stock
        self.profit_target = 0.05  # 盈利目标 5%
        self.stop_loss = -0.02     # 止损线 -2%

    def get_historical_data(self, days=30):
        """获取历史数据"""
        try:
            df = ts.get_k_data(self.stock.code, start=(datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d'))
            return df
        except Exception as e:
            print(f"获取股票 {self.stock.code} 历史数据时出错: {str(e)}")
            return None

    def calculate_signals(self):
        """计算买卖信号"""
        df = self.get_historical_data()
        if df is None or len(df) < 26:  # 确保有足够的数据计算指标
            return None

        # 计算MACD
        exp1 = df['close'].ewm(span=12, adjust=False).mean()
        exp2 = df['close'].ewm(span=26, adjust=False).mean()
        macd = exp1 - exp2
        signal = macd.ewm(span=9, adjust=False).mean()
        df['macd_hist'] = macd - signal
        
        # 计算RSI
        delta = df['close'].diff()
        gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
        loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
        rs = gain / loss
        df['rsi'] = 100 - (100 / (1 + rs))

        # 计算成交量5日均线
        df['volume_ma5'] = df['volume'].rolling(window=5).mean()

        # 生成买入信号
        df['buy_signal'] = False
        
        # MACD金叉：当日MACD柱由负变正
        macd_cross = (df['macd_hist'].shift(1) < 0) & (df['macd_hist'] > 0)
        
        # 成交量大于5日均线
        volume_condition = df['volume'] > df['volume_ma5']
        
        # RSI小于65
        rsi_condition = df['rsi'] < 65

        # 综合买入条件
        df.loc[macd_cross & volume_condition & rsi_condition, 'buy_signal'] = True

        return df

    def analyze_position(self, entry_price):
        """分析持仓状态，返回是否应该卖出"""
        current_price = float(self.stock.last_price)
        if current_price is None:
            return False, 0

        profit_ratio = (current_price - entry_price) / entry_price
        
        # 判断是否达到盈利目标或止损线
        if profit_ratio >= self.profit_target or profit_ratio <= self.stop_loss:
            return True, profit_ratio
            
        return False, profit_ratio

    def get_trading_suggestion(self):
        """获取交易建议"""
        df = self.calculate_signals()
        if df is None or len(df) == 0:
            return {
                'code': self.stock.code,
                'name': self.stock.name,
                'suggestion': '无法获取足够的历史数据',
                'reason': '数据不足'
            }

        latest_data = df.iloc[-1]
        
        # 检查是否有买入信号
        if latest_data['buy_signal']:
            return {
                'code': self.stock.code,
                'name': self.stock.name,
                'suggestion': '买入',
                'reason': f"MACD金叉，成交量放大，RSI={latest_data['rsi']:.2f}",
                'current_price': self.stock.last_price,
                'profit_target': self.stock.last_price * (1 + self.profit_target),
                'stop_loss': self.stock.last_price * (1 + self.stop_loss)
            }
        
        return {
            'code': self.stock.code,
            'name': self.stock.name,
            'suggestion': '观望',
            'reason': '未满足买入条件'
        } 